import { IParamsResult } from '@/shared/core/decorator/ListParams.decorator'
import { HttpException, HttpStatus, Injectable, Logger } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { Repository } from 'typeorm'
import { CreateBackendDto } from './dto/create-backend.dto'
import { UpdateBackendDto } from './dto/update-backend.dto'
import { BackendEntity } from './entities/backend.entity'

@Injectable()
export class BackendService {
  constructor(
    @InjectRepository(BackendEntity)
    private readonly backendRepository: Repository<BackendEntity>,
  ) {}

  async create(dto: CreateBackendDto) {
    const result = await this.backendRepository.create(dto)
    await this.backendRepository.save(result)

    return result
  }

  findAll({ where, order }: IParamsResult) {
    return this.backendRepository.find({ order, where })
  }

  // 详情
  findOne(id) {
    return this.backendRepository.findOne({ where: { id } })
  }

  // 修改
  async update(id, dto: UpdateBackendDto) {
    const old = await this.findOne(id)
    const vo = await this.backendRepository.merge(old, dto)

    return this.backendRepository.save(vo)
  }

  // 删除
  async remove(id) {
    const result = await this.backendRepository.delete(id)
    Logger.log(`删除返回数据：${JSON.stringify(result)}`)

    return result.affected || new HttpException('无法删除，请稍候在试', HttpStatus.BAD_REQUEST)
  }
}
